package org.springblade.report.provider;

import com.bstek.ureport.exception.ReportComputeException;
import com.bstek.ureport.provider.image.ImageProvider;
import org.springblade.core.tool.utils.ImageUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import java.net.URL;

/**
 * 更改图片尺寸提供类
 */
@Configuration
public class ImageSizeProvider implements ImageProvider, ApplicationContextAware {

	private ApplicationContext applicationContext;
	private String baseWebPath;

	@Override
	public InputStream getImage(String path) {
		try {
			if (path.startsWith("http://") || path.startsWith("https://")) {
				BufferedImage bufferedImage = ImageUtil.readImage(new URL(path));
				String fileType = path.substring(path.lastIndexOf(".") + 1);
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				/**
				 * 缩放图像（按高度和宽度缩放）
				 *
				 * @param src 源图像
				 * @param output 输出流
				 * @param type 类型
				 * @param height 缩放后的高度
				 * @param width 缩放后的宽度
				 * @param bb 比例不对时是否需要补白：true为补白; false为不补白;
				 * @param fillColor 填充色，null时为Color.WHITE
				 */
				int picWidth = bufferedImage.getWidth();
				int picHeight = bufferedImage.getHeight();
				if (picWidth > 600 || picHeight > 800) {
					double scale = 0;
					if (picWidth > picHeight){
						scale = 600d/picWidth;
					}else {
						scale = 800d/picHeight;
					}
					//ImageUtil.zoomFixed(bufferedImage, outputStream, fileType, 450, 600, false, null);
					//true 放大，false=缩小
					//ImageUtil.zoomScale(bufferedImage, outputStream, fileType, scale, false);
					int width = Long.valueOf(Math.round((double)picWidth * scale)).intValue();
					int height = Long.valueOf(Math.round((double)picHeight * scale)).intValue();
					//平滑
					Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
					BufferedImage tag = new BufferedImage(width, height, 1);
					Graphics g = tag.getGraphics();
					g.drawImage(image, 0, 0, (ImageObserver)null);
					g.dispose();
					ImageIO.write(tag, fileType, outputStream);
					outputStream.close();
				}
				else {
					ImageUtil.convert(bufferedImage, outputStream, fileType);
				}
				InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
				return inputStream;
			}
			return new FileInputStream(path);

		}catch (Exception e){
			throw new ReportComputeException(e);
		}
	}

	@Override
	public boolean support(String path) {
		if (path.startsWith("http://") || path.startsWith("https://")) {
			return true;
		}
//		else if(baseWebPath!=null && (path.startsWith("/") || path.startsWith("/WEB-INF"))){
//			return true;
//		}
		return false;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if(applicationContext instanceof WebApplicationContext){
			WebApplicationContext context = (WebApplicationContext) applicationContext;
			baseWebPath = context.getServletContext().getRealPath("/");
		}
		this.applicationContext = applicationContext;
	}
}
